import type {
	SopDocumentManage,
	SopDocument,
	SopDocumentProduct,
	SopAttachment,
	SopSendRecord,
} from "@/pages/mes/sop/entity";
import apiClient from "../../apiClient";

export interface PageListReq {
	//文档编码
	code?: string;
	//文档名称
	name?: string;
	//文档类型
	type?: string;
	//状态
	status?: string;
	//当前页码
	page: number;
	//每页数量
	pageSize: number;
}

export interface PageListRes {
	//总记录数
	total: number;
	//数据列表
	records: SopDocumentManage[];
}

const pageList = (data: PageListReq): Promise<PageListRes> =>
	apiClient.post({
		url: "/mes/sop/manage/pageList",
		data,
	});
const getInfo = (id: React.Key): Promise<SopDocumentManage> =>
	apiClient.get({
		url: `/mes/sop/manage/${id}`,
	});

const add = (data: SopDocumentManage): Promise<SopDocumentManage> =>
	apiClient.post({
		url: "/mes/sop/manage",
		data,
	});

const update = (data: SopDocumentManage): Promise<SopDocumentManage> =>
	apiClient.put({
		url: "/mes/sop/manage",
		data,
	});

const remove = (ids: React.Key[]): Promise<void> =>
	apiClient.delete({
		url: "/mes/sop/manage",
		params: {
			ids: ids.join(","),
		},
	});
const getdocuments = (id: React.Key): Promise<SopDocument[]> =>
	apiClient.post({
		url: "/mes/sop/document/list",
		data: {
			manageId: id,
		},
	});

const getproducts = (id: React.Key): Promise<SopDocumentProduct[]> =>
	apiClient.post({
		url: "/mes/sop/product/list",
		data: {
			manageId: id,
		},
	});

//上传文件
const uploadFile = (file: File) => {
	const formData = new FormData();
	formData.append("file", file);

	return apiClient.post<SopAttachment>({
		url: "/mes/sop/attachment/upload",
		data: formData,
		headers: {
			// 不要手动设置Content-Type，让浏览器自动处理
			// 浏览器会自动设置正确的Content-Type和boundary
		},
	});
};

// 删除文件
const deleteFile = (attachmentId: React.Key): Promise<void> =>
	apiClient.delete({
		url: `/mes/sop/attachment/${attachmentId}`,
	});

// 更新文档状态
const updateStatus = (ids: React.Key[], status: string): Promise<void> =>
	apiClient.put({
		url: `/mes/sop/manage/status/${status}`,
		params: {
			ids: ids.join(","),
		},
	});

// 发送文档
const sendDoc = (data: SopSendRecord[]): Promise<void> =>
	apiClient.post({
		url: "/mes/sop/manage/sendDoc",
		data,
	});

export const sopDocumentManageService = {
	pageList,
	getInfo,
	add,
	update,
	remove,
	getdocuments,
	getproducts,
	uploadFile,
	deleteFile,
	updateStatus,
	sendDoc,
};

export default sopDocumentManageService;
